package org.jeecg.modules.tigstatics.controller;

import java.time.LocalDate;
import java.util.Arrays;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.service.DeviceService;
import org.jeecg.modules.tigstatics.entity.TigStatistics;
import org.jeecg.modules.tigstatics.service.ITigStatisticsService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.springframework.core.env.Environment;

/**
 * @Description: 统计表
 * @Author: jeecg-boot
 * @Date: 2023-08-25
 * @Version: V1.0
 */
@Api(tags = "统计表")
@RestController
@RequestMapping("/tigstatics/tigStatistics")
@Slf4j
public class TigStatisticsController extends JeecgController<TigStatistics, ITigStatisticsService> {
    @Autowired
    private ITigStatisticsService tigStatisticsService;
    @Autowired
    private DeviceService deviceService;
    //    @Autowired
//    private ISysDepartService sysDepartService;
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private Environment environment;

    /**
     * 分页列表查询
     *
     * @param tigStatistics
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "统计表-分页列表查询")
    @ApiOperation(value = "统计表-分页列表查询", notes = "统计表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<TigStatistics>> queryPageList(TigStatistics tigStatistics,
                                                      @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                      HttpServletRequest req) {
        QueryWrapper<TigStatistics> queryWrapper = QueryGenerator.initQueryWrapper(tigStatistics, req.getParameterMap());
        Page<TigStatistics> page = new Page<TigStatistics>(pageNo, pageSize);
        IPage<TigStatistics> pageList = tigStatisticsService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param tigStatistics
     * @return
     */
    @AutoLog(value = "统计表-添加")
    @ApiOperation(value = "统计表-添加", notes = "统计表-添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody TigStatistics tigStatistics) {
        tigStatisticsService.save(tigStatistics);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param tigStatistics
     * @return
     */
    @AutoLog(value = "统计表-编辑")
    @ApiOperation(value = "统计表-编辑", notes = "统计表-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody TigStatistics tigStatistics) {
        tigStatisticsService.updateById(tigStatistics);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "统计表-通过id删除")
    @ApiOperation(value = "统计表-通过id删除", notes = "统计表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        tigStatisticsService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "统计表-批量删除")
    @ApiOperation(value = "统计表-批量删除", notes = "统计表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.tigStatisticsService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "统计表-通过id查询")
    @ApiOperation(value = "统计表-通过id查询", notes = "统计表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<TigStatistics> queryById(@RequestParam(name = "id", required = true) String id) {
        TigStatistics tigStatistics = tigStatisticsService.getById(id);
        if (tigStatistics == null) {
            return Result.error("未找到对应数据", null);
        }
        return Result.OK(tigStatistics);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param tigStatistics
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, TigStatistics tigStatistics) {
        return super.exportXls(request, tigStatistics, TigStatistics.class, "统计表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, TigStatistics.class);
    }

    /**
     * 获取当前设备在线、离线、报警统计数据
     */
    @ApiOperation(value = "当前统计数据", notes = "当前统计数据")
    @GetMapping(value = "/queryStatistics")
    public Result<TigStatistics> queryStatistics(@RequestParam(name = "departId", required = true) String departId) {
        TigStatistics statics = new TigStatistics();
        //无法直接引用sysDepart的bean，涉及到maven互相引用冲突，只能远程调用
        String port = environment.getProperty("server.port");
        ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://localhost:"+port+"/tiger-power/sys/sysDepart/getDepartInfo?departId="+departId, String.class);
        String body = responseEntity.getBody();
        JSONObject obj = JSONObject.parseObject(body);
        JSONObject result = obj.getJSONObject("result");
        String orgCode = result.getString("orgCode");
        int onlineCount = deviceService.getOnlineDevicesCount(orgCode);
        int offlineCount = deviceService.getOfflineDevicesCount(orgCode);
        int deviceCount = deviceService.getDevicesCount(orgCode);
        int warningCount = deviceService.getWarningCount(orgCode, -1, LocalDate.now());
        int cityVolCount = deviceService.getWarningCount(orgCode, 1, LocalDate.now());
        int mVolCount = deviceService.getWarningCount(orgCode, 2, LocalDate.now());
        int bVolCount = deviceService.getWarningCount(orgCode, 3, LocalDate.now());
        int curCount = deviceService.getWarningCount(orgCode, 4, LocalDate.now());
        int upsCount = deviceService.getWarningCount(orgCode, 5, LocalDate.now());
        int tempCount = deviceService.getWarningCount(orgCode, 6, LocalDate.now());
        int channelCount = deviceService.getWarningCount(orgCode, 7, LocalDate.now());
        statics.setDevOnlineCount(onlineCount);
        statics.setDevOfflineCount(offlineCount);
        statics.setDeviceCount(deviceCount);
        statics.setDevWarningCount(warningCount);
        statics.setCityvolWarningCount(cityVolCount);
        statics.setMainvolWarningCount(mVolCount);
        statics.setBackvolWarningCount(bVolCount);
        statics.setCurrentWarningCount(curCount);
        statics.setUpsWarningCount(upsCount);
        statics.setTempWarningCount(tempCount);
        statics.setOtherWarningCount(channelCount);
        statics.setDevExcProcCount(0);
        statics.setOrgCode(orgCode);
        return Result.OK(statics);
    }

    /**
     * 获取当前设备在线、离线、报警统计数据
     */
    @ApiOperation(value = "当前统计数据", notes = "当前统计数据")
    @GetMapping(value = "/queryStatisticsdays")
    public Result<Map<String, TigStatistics>> queryStatisticsdays(@RequestParam(name = "departId", required = true) String departId,
                                                                  @RequestParam(name = "days", required = true) Integer days) {
        TigStatistics statics = new TigStatistics();
        String port = environment.getProperty("server.port");
        ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://localhost:"+port+"/tiger-power/sys/sysDepart/getDepartInfo?departId="+departId, String.class);
        String body = responseEntity.getBody();
        JSONObject obj = JSONObject.parseObject(body);
        JSONObject result = obj.getJSONObject("result");
        String orgCode = result.getString("orgCode");
        Map<String, TigStatistics> listStatistics = tigStatisticsService.getWarningCountBydays(orgCode, days);
        return Result.OK(listStatistics);
    }
}
